/**
 * 收入记录权限实际测试脚本
 * 模拟真实环境测试权限控制
 */

const db = uniCloud.database();
const _ = db.command;

// 导入权限检查函数
const { 
  checkIncomeRecordViewPermission, 
  checkIncomeRecordEditPermission, 
  checkIncomeRecordDeletePermission, 
  checkIncomeRecordAddPermission 
} = require('common/dh-common/permission-utils');

/**
 * 测试收入记录列表查询的权限过滤
 */
async function testIncomeRecordListPermission() {
  console.log('=== 测试收入记录列表查询权限过滤 ===');
  
  try {
    // 获取所有用户
    const users = await db.collection('uni-id-users').get();
    console.log(`找到 ${users.data.length} 个用户`);
    
    // 对每个用户测试列表查询权限
    for (const user of users.data) {
      const roles = Array.isArray(user.role) ? user.role : [user.role].filter(Boolean);
      if (roles.length === 0) continue;
      
      console.log(`\n--- 测试用户: ${user._id} (角色: ${roles.join(', ')}) ---`);
      
      // 构建查询条件
      let query = { is_deleted: false };
      
      // 根据用户角色构建查询条件
      const canViewAll = roles.some(role => ['admin', 'director', 'finance'].includes(role));
      const canViewExcludeDirector = roles.some(role => ['vice_director'].includes(role));
      const canViewSelf = roles.some(role => ['head_nurse', 'administrative', 'purchaser'].includes(role));
      
      if (canViewAll) {
        console.log('可以查看所有记录');
      } else if (canViewExcludeDirector) {
        console.log('可以查看除院长外的所有记录');
        // 获取院长用户ID
        const directorUsers = await db.collection('uni-id-users')
          .where({ role: 'director' })
          .field({ _id: true })
          .get();
        
        const directorIds = directorUsers.data.map(d => d._id);
        if (directorIds.length > 0) {
          query.user_id = _.nin(directorIds);
        }
      } else if (canViewSelf) {
        console.log('只能查看自己的记录');
        query.user_id = user._id;
      } else {
        console.log('无权查看收入记录');
        continue;
      }
      
      // 执行查询
      const res = await db.collection('dh-income_records')
        .where(query)
        .limit(5)
        .get();
      
      console.log(`查询到 ${res.data.length} 条记录`);
    }
  } catch (error) {
    console.error('测试列表查询权限失败:', error);
  }
}

/**
 * 测试单个记录的权限检查
 */
async function testIncomeRecordPermission() {
  console.log('\n=== 测试单个记录的权限检查 ===');
  
  try {
    // 获取一条收入记录
    const records = await db.collection('dh-income_records').limit(1).get();
    if (records.data.length === 0) {
      console.log('没有找到收入记录，跳过测试');
      return;
    }
    
    const record = records.data[0];
    console.log(`测试记录ID: ${record._id}, 所有者: ${record.user_id}`);
    
    // 获取所有用户
    const users = await db.collection('uni-id-users').get();
    
    // 对每个用户测试权限
    for (const user of users.data) {
      const roles = Array.isArray(user.role) ? user.role : [user.role].filter(Boolean);
      if (roles.length === 0) continue;
      
      console.log(`\n--- 测试用户: ${user._id} (角色: ${roles.join(', ')}) ---`);
      
      // 测试查看权限
      const viewResult = await checkIncomeRecordViewPermission(user._id, record.user_id);
      console.log(`查看权限: ${viewResult.hasPermission ? '✓' : '✗'} ${viewResult.reason || ''}`);
      
      // 测试编辑权限
      const editResult = await checkIncomeRecordEditPermission(user._id, record.user_id);
      console.log(`编辑权限: ${editResult.hasPermission ? '✓' : '✗'} ${editResult.reason || ''}`);
      
      // 测试删除权限
      const deleteResult = await checkIncomeRecordDeletePermission(user._id, record.user_id);
      console.log(`删除权限: ${deleteResult.hasPermission ? '✓' : '✗'} ${deleteResult.reason || ''}`);
    }
  } catch (error) {
    console.error('测试单个记录权限失败:', error);
  }
}

/**
 * 测试添加权限
 */
async function testAddPermission() {
  console.log('\n=== 测试添加权限 ===');
  
  try {
    // 获取所有用户
    const users = await db.collection('uni-id-users').get();
    
    // 对每个用户测试添加权限
    for (const user of users.data) {
      const roles = Array.isArray(user.role) ? user.role : [user.role].filter(Boolean);
      if (roles.length === 0) continue;
      
      console.log(`\n--- 测试用户: ${user._id} (角色: ${roles.join(', ')}) ---`);
      
      // 测试添加权限
      const addResult = await checkIncomeRecordAddPermission(user._id);
      console.log(`添加权限: ${addResult.hasPermission ? '✓' : '✗'} ${addResult.reason || ''}`);
    }
  } catch (error) {
    console.error('测试添加权限失败:', error);
  }
}

/**
 * 运行所有测试
 */
async function runAllTests() {
  console.log('开始运行收入记录权限实际测试...\n');
  
  await testIncomeRecordListPermission();
  await testIncomeRecordPermission();
  await testAddPermission();
  
  console.log('\n所有测试完成!');
}

// 导出测试函数
module.exports = { 
  testIncomeRecordListPermission,
  testIncomeRecordPermission,
  testAddPermission,
  runAllTests
};